require 'digest/sha1'

class User < ActiveRecord::Base
    validates_presence_of :lastname, :firstname, :login
    
    validates_uniqueness_of :login
    validates_confirmation_of :password
    
    attr_reader :password
    attr_accessor :password_confirmation
    
    def password=(value)
        @password = value
        self.salt = create_new_salt
        self.hashed_password = self.class.encrypt_password(salt, value)
    end

    def validate
        errors.add(:password, 'is missing') if hashed_password.blank?
    end

    def self.authenticate(login, password)
        user = find_by_login(login)
        if user
            expected_pass = encrypt_password(user.salt, password)
            user = nil if expected_pass != user.hashed_password
        end
        user
    end

private
    def create_new_salt
        self.object_id.to_s + rand.to_s
    end

    def self.encrypt_password(salt, pass)
        Digest::SHA1.hexdigest(salt + 'insia' + pass)
    end

end
